/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nms.base;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;

/**
 *
 * @author mohamedemara
 */
public abstract class ObjectPool<T> {

    private long expireTime;
    private Hashtable<T, Long> locked;
    private Hashtable<T, Long> unlocked;

    public ObjectPool() {
    locked=new Hashtable<T, Long>();
    unlocked=new Hashtable<T, Long>();
    }

    
    protected abstract T create();

    public abstract boolean validate(T obj);

    public abstract void expire(T obj);

    public synchronized T checkOut() {
        long now = System.currentTimeMillis();
        T o = null;
        if (unlocked.size() > 0) {
            Enumeration<T> enu = locked.keys();
            while (enu.hasMoreElements()) {
                o = enu.nextElement();
                if (now - unlocked.get(o) > expireTime) {
                    unlocked.remove(o);
                    expire(o);
                    o = null;
                } else {
                    if (validate(o)) {
                        unlocked.remove(o);
                        locked.put(o, now);
                        return o;
                    } else {
                        unlocked.remove(o);
                        expire(o);
                        o = null;
                    }
                }
            }
        }
        o = create();
        locked.put(o, now);
        return o;
    }

    public synchronized void checkIn(T o) {
        long now = System.currentTimeMillis();
        locked.remove(o);
        unlocked.put(o, now);
    }
}
